/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation. 
 *
 * This source code is subject to terms and conditions of the Microsoft Public License. A 
 * copy of the license can be found in the License.html file at the root of this distribution. If 
 * you cannot locate the  Microsoft Public License, please send an email to 
 * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Microsoft Public License.
 *
 * You must not remove this notice, or any other, from this software.
 *
 *
 * ***************************************************************************/

using System;
using System.Diagnostics;
using System.Reflection.Emit;
using Microsoft.Contracts;
using Microsoft.Scripting.Utils;

namespace Microsoft.Scripting.Generation {
    /// <summary>
    /// A slot that can be used to wrap other slots and perform a cast before
    /// getting or setting the value.
    /// </summary>
    internal sealed class CastSlot : Slot {
        private readonly Slot _instance;
        private readonly Type _type;

        private CastSlot(Type type, Slot instance) {
            Assert.NotNull(instance, type);
            Debug.Assert(type.IsVisible);
            Debug.Assert(type != instance.Type);
            Debug.Assert(!type.IsValueType || instance.Type == typeof(object));

            _instance = instance;
            _type = type;
        }

        // Wraps slot in a cast slot if the types are different
        internal static Slot Cast(Type type, Slot slot) {
            return (type == slot.Type) ? slot : new CastSlot(type, slot);
        }

        public override void EmitGet(ILGen cg) {
            _instance.EmitGet(cg);
            if (_type.IsValueType) {
                cg.Emit(OpCodes.Unbox_Any, _type);
            } else {
                cg.Emit(OpCodes.Castclass, _type);
            }
        }

        public override void EmitGetAddr(ILGen cg) {
            throw new NotImplementedException(ResourceUtils.GetString(ResourceUtils.NotImplemented));
        }

        public override void EmitSet(ILGen cg) {
            if (_type.IsValueType) {
                cg.Emit(OpCodes.Box, _type);
            } else {
                cg.Emit(OpCodes.Castclass, _instance.Type);
            }
            _instance.EmitSet(cg);
        }

        public override Type Type {
            get {
                return _type;
            }
        }

        [Confined]
        public override string/*!*/ ToString() {
            return String.Format("CastSlot From: ({0}) To: {1}", _instance, _type);
        }
    }
}
